package cn.yuanqiao.activiti.service.impl;

import cn.yuanqiao.activiti.service.ISysFileService;
import cn.yuanqiao.activiti.utils.FileUploadUtils;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.file.FileUtils;
import cn.yuanqiao.system.domain.SysFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 本地文件存储
 * 
 * @author ruoyi
 */
@Primary
@Service
public class LocalSysFileServiceImpl implements ISysFileService
{

    private static final Logger log = LoggerFactory.getLogger(LocalSysFileServiceImpl.class);
    /**
     * 资源映射路径 前缀
     */
    @Value("${file.prefix}")
    public String localFilePrefix;

    /**
     * 域名或本机访问地址
     */
    @Value("${file.domain}")
    public String domain;
    
    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.path}")
    private String localFilePath;

    /**
     * 本地文件上传接口
     * 
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file) throws Exception
    {
        String name = FileUploadUtils.upload(localFilePath, file);
        String url = domain + localFilePrefix + name;
        return url;
    }

    @Override
    public R<SysFile> upload(MultipartFile file) {
        try
        {
            // 上传并返回访问地址
            String url = uploadFile(file);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            return R.ok(sysFile);
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    @Override
    public ResponseEntity<Resource> statics(String path) throws UnsupportedEncodingException {
        String realPath = localFilePath+ File.separator+path;
        Path filePath = Paths.get(realPath);
        Resource resource = null;
        try {
            resource = new UrlResource(filePath.toUri());
        } catch (MalformedURLException e) {
            throw new ServiceException(e.getMessage());
        }

        if (resource.exists() || resource.isReadable()) {
            String fileName= URLEncoder.encode(resource.getFilename(), "UTF-8");
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
                    .body(resource);
        } else {
            throw new ServiceException("Could not find the file!");
        }
    }


}
